﻿using AcexeService.Models;
using AcexeService.ServiceModel.Sys;
using ServiceStack;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;

//https://github.com/ServiceStack/ServiceStack.OrmLite
namespace AcexeService.ServiceInterface
{
    [Authenticate]
    public class SysUserServices : Service
    {
        /// <summary>
        /// 通过用户帐号(UserAccount)取用户实体数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetUserSession request)
        {
            var list = Db.Select<SYS_USER>(c => c.USERACCOUNT == request.UserAccount);
            if (list.Count > 0)
            {
                list[0].USERPWD = GetSession().Id;
                return list[0];
            }

            return new SYS_USER
            {
                USERPWD = GetSession().Id,
                USERNAME = "未知",
                USERACCOUNT = request.UserAccount
            };
        }

        /// <summary>
        /// 通过用户ID(UserId)取用户实体数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetUser request)
        {
            string queryuserid = request.UserId;
            var list = Db.Select<SYS_USER>(c => c.USERID == queryuserid);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 查询用户数据（分页、导出）
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(GetUserList request)
        {
            var miniuigridmodel = new MiniUiGridModel<SYS_USER>();
            var model = request.SysUserModel;

            var q = Db.From<SYS_USER>();

            if (!string.IsNullOrEmpty(request.FuzzyUserNameUserAccount))
            {
                string key = request.FuzzyUserNameUserAccount;
                q.And(p => p.USERNAME.Contains(key) || p.USERACCOUNT.Contains(key));
            }

            q.And(x => x.ISVALID == model.ISVALID);

            miniuigridmodel.total = Db.Scalar<int>(q.Select(Sql.Count("*")));

            if (!request.Page.IsGetWholeData)
            {
                q.Take(request.Page.PageSize);
                q.Skip(request.Page.PageSize * request.Page.PageIndex);
            }

            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.USERACCOUNT);
            }

            var list = Db.Select<SYS_USER>(q.Select(c => c));
            miniuigridmodel.data = list;

            return miniuigridmodel;
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(AddUser request)
        {
            var dto = new MessageDto();
            var model = request.SysUserModel;

            if (string.IsNullOrEmpty(model.USERID))
            {
                dto.Flag = false;
                dto.Msg = "用户ID不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.USERACCOUNT))
            {
                dto.Flag = false;
                dto.Msg = "用户帐号不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.USERNAME))
            {
                dto.Flag = false;
                dto.Msg = "用户姓名不允许为空";
                return dto;
            }

            try
            {
                Db.Insert<SYS_USER>(model);
                dto.Flag = true;
                dto.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(EditUser request)
        {
            var dto = new MessageDto();
            var model = request.SysUserModel;

            if (string.IsNullOrEmpty(model.USERID))
            {
                dto.Flag = false;
                dto.Msg = "用户ID不允许为空";
                return dto;
            }
            if (string.Equals(model.USERACCOUNT, ""))
            {
                dto.Flag = false;
                dto.Msg = "用户帐号不允许为空";
                return dto;
            }
            // 字段值为null时不会更新数据，但是为""会更新为""
            if (string.Equals(model.USERNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "用户姓名不允许为空";
                return dto;
            }

            try
            {
                var list = Db.Select<SYS_USER>(c => c.USERID == model.USERID);
                if (list.Count == 0)
                {
                    dto.Flag = false;
                    dto.Msg = "您编辑的用户不存在，请刷新页面后重试";
                    return dto;
                }

                var editmodel = list[0];
                editmodel = AcexeService.ServiceInterface.Lib.AutoTransfer.GetModel<SYS_USER>(editmodel, model);
                Db.Update<SYS_USER>(editmodel);
                dto.Flag = true;
                dto.Msg = "修改成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(DeleteUser request)
        {
            var dto = new MessageDto();

            if (request.UserId.Count == 0)
            {
                dto.Flag = false;
                dto.Msg = "空记录";
                return dto;
            }

            try
            {
                //只作虚删除
                var userid = request.UserId.ToSqlString();
                Db.ExecuteSql("UPDATE SYS_USER SET ISVALID = @isvalid WHERE USERID IN(" + userid + ")", new { isvalid = 0 });
                dto.Flag = true;
                dto.Msg = "注销成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }
    }

}